package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 孕产期时间设置
 * Created by Administrator on 2016/10/19.
 */
public class YunChanSheZhiActivity extends BaseActivity implements View.OnClickListener {
    private TextView riqi_tv;
    private TextView jisuan_tv;
    private int id;
    private String pageIntent;
    private String yiyuan;
    //数据库
    private DBManager db = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yuchanqi);
        db=new DBManager(this);
        ImageView back = (ImageView) findViewById(R.id.yuchanshezhi_activity_back);
        Button submit_btn = (Button) findViewById(R.id.yuchanshezhi_activity_btn);
        riqi_tv = (TextView) findViewById(R.id.yuchanshezhi_activity_riqi);
        jisuan_tv = (TextView) findViewById(R.id.yuchanshezhi_activity_jisuan);
        back.setOnClickListener(this);
        riqi_tv.setOnClickListener(this);
        jisuan_tv.setOnClickListener(this);
        submit_btn.setOnClickListener(this);
        pageIntent = getIntent().getExtras().getString("PAGE_INTENT");
        yiyuan = db.select("antenatalCareHospitalName");
        id = Integer.parseInt(db.select("antenatalCareHospitalId"));
//        yiyuan = getIntent().getExtras().getString("HOSPTIALNAME");
//        pageIntent = getIntent().getExtras().getString("PAGE_INTENT");
//        id = getIntent().getExtras().getInt("HOSPTIALID");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.yuchanshezhi_activity_back:
                finish();
                break;
            case R.id.yuchanshezhi_activity_riqi:
                Calendar instance = Calendar.getInstance();
                DatePickerDialog pickerDialog = new DatePickerDialog(YunChanSheZhiActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            private StringBuffer stringBuffer;

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                stringBuffer = new StringBuffer("");
                                stringBuffer.append(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ");
                                riqi_tv.setText("" + stringBuffer);
                            }
                        }, instance.get(Calendar.YEAR),
                        instance.get(Calendar.MONTH),
                        instance.get(Calendar.DAY_OF_MONTH));
                pickerDialog.setMessage("请选择预产时间");
                pickerDialog.setCancelable(false);
                pickerDialog.show();
                break;

            case R.id.yuchanshezhi_activity_jisuan:
                Intent intent = new Intent();
                intent.setClass(YunChanSheZhiActivity.this, YuChanJiSuanActivity.class);
                startActivityForResult(intent, 4);
                break;

            //孕期设置提交按钮
            case R.id.yuchanshezhi_activity_btn:
                String mDate=riqi_tv.getText().toString();
                if (mDate != null && !mDate.equals("") && !mDate.equals("null")) {
                    //如果设置的孕期大于等于今天，就提交
                    if (DateUtils.getStringToDate2(mDate) >= DateUtils.getStringToDate2(DateUtils.getCurrentDate())) {
                        //一天的时间戳  86400为一天的时间戳
                        long oneDay = AppConstant.oneDay;
                        if((DateUtils.getStringToDate2 (DateUtils.getCurrentDate())+oneDay*279)>=DateUtils.getStringToDate2 (mDate)){
                            submit(id, mDate);
                        }else{
                            ToastUtil.showToast(this,"请输入正确的预产期时间");
                        }
                    }else{
                        ToastUtil.showToast(this,"请正确设置孕期信息，方便更好的为您服务");
                    }
                } else {
                    ToastUtil.showToast(this,"请正确设置孕期信息，方便更好的为您服务");
                }
                break;

        }
    }

    //加载框
    AlertDialog zhuce_dialog;

    private void submit(final int id, final String date) {
        zhuce_dialog = new MyAlertDialog().ShowDialog(YunChanSheZhiActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    param.put("pregnancyStatus", 1);
                    param.put("preDeliveryDate", date);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.YunChan_Sumit).addHeader("Authorization",db.select("token_type")+" " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (zhuce_dialog != null) {
                zhuce_dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(YunChanSheZhiActivity.this, "设置成功");
                    if (pageIntent != null && yiyuan != null) {
                        sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                    } else {
                        Toast.makeText(YunChanSheZhiActivity.this, "设置失败", Toast.LENGTH_SHORT).show();
                    }
                    finish();

                    break;
                case 1:
                    ToastUtil.showToast(YunChanSheZhiActivity.this, "设置失败");

                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String shijian = data.getExtras().getString("shijian");
        String[] strs = shijian.split("T");
        riqi_tv.setText(strs[0].replace("\"", ""));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
